package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.regex.Pattern;

@WebFilter(filterName = "checkLoginFilter", urlPatterns = "/*")
@Slf4j
public class CheckLoginFilter implements Filter {
    //路径匹配,支持通配符
    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    /**
     * 检查用户是否登录
     *
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //获得当前线程的id
        long id = Thread.currentThread().getId();
        log.info("线程id为：{}", id);

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1`获取本次请求的uri
        String requestURI = request.getRequestURI();// /backend/index.html
        log.info("拦截到请求:{}", requestURI);
        //2`定义可以直接放行的uri
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login"
        };
        //3`判断本次请求是否可以直接放行
        boolean check = check(urls, requestURI);

        //4`如果可以直接放行
        if (check) {
            log.info("本次请求不需要处理", requestURI);
            filterChain.doFilter(request, response);
            return;
        }

        //4.2判断登录状态,如果已登录,则直接放行
        if (request.getSession().getAttribute("user") != null) {
            log.info("用户已登录id为:{}", request.getSession().getAttribute("user"));
            Long userId = (Long) request.getSession().getAttribute("user");

            BaseContext.setCurrentId(userId);

            filterChain.doFilter(request, response);
            return;
        }
        //5`如果不行检查session
        HttpSession session = request.getSession();

        Long empId = (Long) session.getAttribute("employee");
        if (empId != null) {
            //设置当前登录员工id
            BaseContext.setCurrentId(empId);
            //6如果已登录放行
            filterChain.doFilter(request, response);
            return;
        }

        //7`如果未登录就返回登录界面
        R<Object> r = R.error("NOTLOGIN");
        response.getWriter().write(JSON.toJSONString(r));
    }

    /**
     * 路径匹配,检查本次是否可以直接放行
     *
     * @param urls
     * @param requestURI
     * @return
     */
    private boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        boolean match = PATH_MATCHER.match("/backend/**", "/backend/index.html");
        System.out.println(match);
    }
}


